package com.test.web3j.util;

import java.io.IOException;
import java.math.BigDecimal;

import org.web3j.protocol.admin.methods.response.NewAccountIdentifier;
import org.web3j.protocol.admin.methods.response.PersonalUnlockAccount;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.response.EthGetBalance;
import org.web3j.utils.Convert;
import org.web3j.utils.Convert.Unit;

import com.test.web3j.Web3JClient;

/**
 * AccountUtil 工具类
 */
public class AccountUtil {
	
	/**
	 * 创建账户
	 * @param password
	 * @return 账号ID
	 * @throws IOException 
	 */
	public String newAccount(String password) throws IOException {
		NewAccountIdentifier newAccount = Web3JClient.getAdmin()
				.personalNewAccount(password).send();
		if(newAccount!=null){
			return newAccount.getAccountId();
		}
		return null;
	}

	/**
	 * 查询账户余额
	 * @param address
	 * @param unit
	 * @return
	 * @throws IOException
	 */
	public BigDecimal getBalance(String address, Unit unit) throws IOException {
		EthGetBalance ethGetBalance = Web3JClient.getWeb3j()
				.ethGetBalance(address, DefaultBlockParameterName.LATEST).send();
		if(ethGetBalance!=null){
			return Convert.fromWei(ethGetBalance.getBalance().toString(), unit); // 单位转换为指定单位，方便查看
		}
		return null;
	}
	
	/**
	 * 解锁账户，发送交易前需要对账户进行解锁
	 * @param address
	 * @param password
	 * @return
	 * @throws IOException
	 */
	public Boolean unlockAccount(String address, String password) throws IOException {
		PersonalUnlockAccount personalUnlockAccount = Web3JClient.getAdmin()
				.personalUnlockAccount(address, password).send();
		return personalUnlockAccount.getResult();
	}
	
}
